environment.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. """Classes for managing templates and their runtime and compile time
  2. options.
  3. """
  4. import os
  5. import typing
  6. import typing as t
  7. import weakref
  8. from collections import ChainMap
  9. from functools import lru_cache
  10. from functools import partial
  11. from functools import reduce
  12. from types import CodeType
  13. from markupsafe import Markup
  14. from . import nodes
  15. from .compiler import CodeGenerator
  16. from .compiler import generate
  17. from .defaults import BLOCK_END_STRING
  18. from .defaults import BLOCK_START_STRING
  19. from .defaults import COMMENT_END_STRING
  20. from .defaults import COMMENT_START_STRING
  21. from .defaults import DEFAULT_FILTERS
  22. from .defaults import DEFAULT_NAMESPACE
  23. from .defaults import DEFAULT_POLICIES
  24. from .defaults import DEFAULT_TESTS
  25. from .defaults import KEEP_TRAILING_NEWLINE
  26. from .defaults import LINE_COMMENT_PREFIX
  27. from .defaults import LINE_STATEMENT_PREFIX
  28. from .defaults import LSTRIP_BLOCKS
  29. from .defaults import NEWLINE_SEQUENCE
  30. from .defaults import TRIM_BLOCKS
  31. from .defaults import VARIABLE_END_STRING
  32. from .defaults import VARIABLE_START_STRING
  33. from .exceptions import TemplateNotFound
  34. from .exceptions import TemplateRuntimeError
  35. from .exceptions import TemplatesNotFound
  36. from .exceptions import TemplateSyntaxError
  37. from .exceptions import UndefinedError
  38. from .lexer import get_lexer
  39. from .lexer import Lexer
  40. from .lexer import TokenStream
  41. from .nodes import EvalContext
  42. from .parser import Parser
  43. from .runtime import Context
  44. from .runtime import new_context
  45. from .runtime import Undefined
  46. from .utils import _PassArg
  47. from .utils import concat
  48. from .utils import consume
  49. from .utils import import_string
  50. from .utils import internalcode
  51. from .utils import LRUCache
  52. from .utils import missing
  53. if t.TYPE_CHECKING:
  54. import typing_extensions as te
  55. from .bccache import BytecodeCache
  56. from .ext import Extension
  57. from .loaders import BaseLoader
  58. _env_bound = t.TypeVar("_env_bound", bound="Environment")
  59. # for direct template usage we have up to ten living environments
  60. @lru_cache(maxsize=10)
  61. def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound:
  62. """Return a new spontaneous environment. A spontaneous environment
  63. is used for templates created directly rather than through an
  64. existing environment.
  65. :param cls: Environment class to create.
  66. :param args: Positional arguments passed to environment.
  67. """
  68. env = cls(*args)
  69. env.shared = True
  70. return env
  71. def create_cache(
  72. size: int,
  73. ) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
  74. """Return the cache class for the given size."""
  75. if size == 0:
  76. return None
  77. if size < 0:
  78. return {}
  79. return LRUCache(size) # type: ignore
  80. def copy_cache(
  81. cache: t.Optional[t.MutableMapping],
  82. ) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
  83. """Create an empty copy of the given cache."""
  84. if cache is None:
  85. return None
  86. if type(cache) is dict:
  87. return {}
  88. return LRUCache(cache.capacity) # type: ignore
  89. def load_extensions(
  90. environment: "Environment",
  91. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]],
  92. ) -> t.Dict[str, "Extension"]:
  93. """Load the extensions from the list and bind it to the environment.
  94. Returns a dict of instantiated extensions.
  95. """
  96. result = {}
  97. for extension in extensions:
  98. if isinstance(extension, str):
  99. extension = t.cast(t.Type["Extension"], import_string(extension))
  100. result[extension.identifier] = extension(environment)
  101. return result
  102. def _environment_config_check(environment: "Environment") -> "Environment":
  103. """Perform a sanity check on the environment."""
  104. assert issubclass(
  105. environment.undefined, Undefined
  106. ), "'undefined' must be a subclass of 'jinja2.Undefined'."
  107. assert (
  108. environment.block_start_string
  109. != environment.variable_start_string
  110. != environment.comment_start_string
  111. ), "block, variable and comment start strings must be different."
  112. assert environment.newline_sequence in {
  113. "\r",
  114. "\r\n",
  115. "\n",
  116. }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."
  117. return environment
  118. class Environment:
  119. r"""The core component of Jinja is the `Environment`. It contains
  120. important shared variables like configuration, filters, tests,
  121. globals and others. Instances of this class may be modified if
  122. they are not shared and if no template was loaded so far.
  123. Modifications on environments after the first template was loaded
  124. will lead to surprising effects and undefined behavior.
  125. Here are the possible initialization parameters:
  126. `block_start_string`
  127. The string marking the beginning of a block. Defaults to ``'{%'``.
  128. `block_end_string`
  129. The string marking the end of a block. Defaults to ``'%}'``.
  130. `variable_start_string`
  131. The string marking the beginning of a print statement.
  132. Defaults to ``'{{'``.
  133. `variable_end_string`
  134. The string marking the end of a print statement. Defaults to
  135. ``'}}'``.
  136. `comment_start_string`
  137. The string marking the beginning of a comment. Defaults to ``'{#'``.
  138. `comment_end_string`
  139. The string marking the end of a comment. Defaults to ``'#}'``.
  140. `line_statement_prefix`
  141. If given and a string, this will be used as prefix for line based
  142. statements. See also :ref:`line-statements`.
  143. `line_comment_prefix`
  144. If given and a string, this will be used as prefix for line based
  145. comments. See also :ref:`line-statements`.
  146. .. versionadded:: 2.2
  147. `trim_blocks`
  148. If this is set to ``True`` the first newline after a block is
  149. removed (block, not variable tag!). Defaults to `False`.
  150. `lstrip_blocks`
  151. If this is set to ``True`` leading spaces and tabs are stripped
  152. from the start of a line to a block. Defaults to `False`.
  153. `newline_sequence`
  154. The sequence that starts a newline. Must be one of ``'\r'``,
  155. ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
  156. useful default for Linux and OS X systems as well as web
  157. applications.
  158. `keep_trailing_newline`
  159. Preserve the trailing newline when rendering templates.
  160. The default is ``False``, which causes a single newline,
  161. if present, to be stripped from the end of the template.
  162. .. versionadded:: 2.7
  163. `extensions`
  164. List of Jinja extensions to use. This can either be import paths
  165. as strings or extension classes. For more information have a
  166. look at :ref:`the extensions documentation <jinja-extensions>`.
  167. `optimized`
  168. should the optimizer be enabled? Default is ``True``.
  169. `undefined`
  170. :class:`Undefined` or a subclass of it that is used to represent
  171. undefined values in the template.
  172. `finalize`
  173. A callable that can be used to process the result of a variable
  174. expression before it is output. For example one can convert
  175. ``None`` implicitly into an empty string here.
  176. `autoescape`
  177. If set to ``True`` the XML/HTML autoescaping feature is enabled by
  178. default. For more details about autoescaping see
  179. :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
  180. be a callable that is passed the template name and has to
  181. return ``True`` or ``False`` depending on autoescape should be
  182. enabled by default.
  183. .. versionchanged:: 2.4
  184. `autoescape` can now be a function
  185. `loader`
  186. The template loader for this environment.
  187. `cache_size`
  188. The size of the cache. Per default this is ``400`` which means
  189. that if more than 400 templates are loaded the loader will clean
  190. out the least recently used template. If the cache size is set to
  191. ``0`` templates are recompiled all the time, if the cache size is
  192. ``-1`` the cache will not be cleaned.
  193. .. versionchanged:: 2.8
  194. The cache size was increased to 400 from a low 50.
  195. `auto_reload`
  196. Some loaders load templates from locations where the template
  197. sources may change (ie: file system or database). If
  198. ``auto_reload`` is set to ``True`` (default) every time a template is
  199. requested the loader checks if the source changed and if yes, it
  200. will reload the template. For higher performance it's possible to
  201. disable that.
  202. `bytecode_cache`
  203. If set to a bytecode cache object, this object will provide a
  204. cache for the internal Jinja bytecode so that templates don't
  205. have to be parsed if they were not changed.
  206. See :ref:`bytecode-cache` for more information.
  207. `enable_async`
  208. If set to true this enables async template execution which
  209. allows using async functions and generators.
  210. """
  211. #: if this environment is sandboxed. Modifying this variable won't make
  212. #: the environment sandboxed though. For a real sandboxed environment
  213. #: have a look at jinja2.sandbox. This flag alone controls the code
  214. #: generation by the compiler.
  215. sandboxed = False
  216. #: True if the environment is just an overlay
  217. overlayed = False
  218. #: the environment this environment is linked to if it is an overlay
  219. linked_to: t.Optional["Environment"] = None
  220. #: shared environments have this set to `True`. A shared environment
  221. #: must not be modified
  222. shared = False
  223. #: the class that is used for code generation. See
  224. #: :class:`~jinja2.compiler.CodeGenerator` for more information.
  225. code_generator_class: t.Type["CodeGenerator"] = CodeGenerator
  226. concat = "".join
  227. #: the context class that is used for templates. See
  228. #: :class:`~jinja2.runtime.Context` for more information.
  229. context_class: t.Type[Context] = Context
  230. template_class: t.Type["Template"]
  231. def __init__(
  232. self,
  233. block_start_string: str = BLOCK_START_STRING,
  234. block_end_string: str = BLOCK_END_STRING,
  235. variable_start_string: str = VARIABLE_START_STRING,
  236. variable_end_string: str = VARIABLE_END_STRING,
  237. comment_start_string: str = COMMENT_START_STRING,
  238. comment_end_string: str = COMMENT_END_STRING,
  239. line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
  240. line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
  241. trim_blocks: bool = TRIM_BLOCKS,
  242. lstrip_blocks: bool = LSTRIP_BLOCKS,
  243. newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
  244. keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
  245. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
  246. optimized: bool = True,
  247. undefined: t.Type[Undefined] = Undefined,
  248. finalize: t.Optional[t.Callable[..., t.Any]] = None,
  249. autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
  250. loader: t.Optional["BaseLoader"] = None,
  251. cache_size: int = 400,
  252. auto_reload: bool = True,
  253. bytecode_cache: t.Optional["BytecodeCache"] = None,
  254. enable_async: bool = False,
  255. ):
  256. # !!Important notice!!
  257. # The constructor accepts quite a few arguments that should be
  258. # passed by keyword rather than position. However it's important to
  259. # not change the order of arguments because it's used at least
  260. # internally in those cases:
  261. # - spontaneous environments (i18n extension and Template)
  262. # - unittests
  263. # If parameter changes are required only add parameters at the end
  264. # and don't change the arguments (or the defaults!) of the arguments
  265. # existing already.
  266. # lexer / parser information
  267. self.block_start_string = block_start_string
  268. self.block_end_string = block_end_string
  269. self.variable_start_string = variable_start_string
  270. self.variable_end_string = variable_end_string
  271. self.comment_start_string = comment_start_string
  272. self.comment_end_string = comment_end_string
  273. self.line_statement_prefix = line_statement_prefix
  274. self.line_comment_prefix = line_comment_prefix
  275. self.trim_blocks = trim_blocks
  276. self.lstrip_blocks = lstrip_blocks
  277. self.newline_sequence = newline_sequence
  278. self.keep_trailing_newline = keep_trailing_newline
  279. # runtime information
  280. self.undefined: t.Type[Undefined] = undefined
  281. self.optimized = optimized
  282. self.finalize = finalize
  283. self.autoescape = autoescape
  284. # defaults
  285. self.filters = DEFAULT_FILTERS.copy()
  286. self.tests = DEFAULT_TESTS.copy()
  287. self.globals = DEFAULT_NAMESPACE.copy()
  288. # set the loader provided
  289. self.loader = loader
  290. self.cache = create_cache(cache_size)
  291. self.bytecode_cache = bytecode_cache
  292. self.auto_reload = auto_reload
  293. # configurable policies
  294. self.policies = DEFAULT_POLICIES.copy()
  295. # load extensions
  296. self.extensions = load_extensions(self, extensions)
  297. self.is_async = enable_async
  298. _environment_config_check(self)
  299. def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
  300. """Adds an extension after the environment was created.
  301. .. versionadded:: 2.5
  302. """
  303. self.extensions.update(load_extensions(self, [extension]))
  304. def extend(self, **attributes: t.Any) -> None:
  305. """Add the items to the instance of the environment if they do not exist
  306. yet. This is used by :ref:`extensions <writing-extensions>` to register
  307. callbacks and configuration values without breaking inheritance.
  308. """
  309. for key, value in attributes.items():
  310. if not hasattr(self, key):
  311. setattr(self, key, value)
  312. def overlay(
  313. self,
  314. block_start_string: str = missing,
  315. block_end_string: str = missing,
  316. variable_start_string: str = missing,
  317. variable_end_string: str = missing,
  318. comment_start_string: str = missing,
  319. comment_end_string: str = missing,
  320. line_statement_prefix: t.Optional[str] = missing,
  321. line_comment_prefix: t.Optional[str] = missing,
  322. trim_blocks: bool = missing,
  323. lstrip_blocks: bool = missing,
  324. newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,
  325. keep_trailing_newline: bool = missing,
  326. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
  327. optimized: bool = missing,
  328. undefined: t.Type[Undefined] = missing,
  329. finalize: t.Optional[t.Callable[..., t.Any]] = missing,
  330. autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
  331. loader: t.Optional["BaseLoader"] = missing,
  332. cache_size: int = missing,
  333. auto_reload: bool = missing,
  334. bytecode_cache: t.Optional["BytecodeCache"] = missing,
  335. enable_async: bool = False,
  336. ) -> "Environment":
  337. """Create a new overlay environment that shares all the data with the
  338. current environment except for cache and the overridden attributes.
  339. Extensions cannot be removed for an overlayed environment. An overlayed
  340. environment automatically gets all the extensions of the environment it
  341. is linked to plus optional extra extensions.
  342. Creating overlays should happen after the initial environment was set
  343. up completely. Not all attributes are truly linked, some are just
  344. copied over so modifications on the original environment may not shine
  345. through.
  346. .. versionchanged:: 3.1.2
  347. Added the ``newline_sequence``,, ``keep_trailing_newline``,
  348. and ``enable_async`` parameters to match ``__init__``.
  349. """
  350. args = dict(locals())
  351. del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
  352. rv = object.__new__(self.__class__)
  353. rv.__dict__.update(self.__dict__)
  354. rv.overlayed = True
  355. rv.linked_to = self
  356. for key, value in args.items():
  357. if value is not missing:
  358. setattr(rv, key, value)
  359. if cache_size is not missing:
  360. rv.cache = create_cache(cache_size)
  361. else:
  362. rv.cache = copy_cache(self.cache)
  363. rv.extensions = {}
  364. for key, value in self.extensions.items():
  365. rv.extensions[key] = value.bind(rv)
  366. if extensions is not missing:
  367. rv.extensions.update(load_extensions(rv, extensions))
  368. if enable_async is not missing:
  369. rv.is_async = enable_async
  370. return _environment_config_check(rv)
  371. @property
  372. def lexer(self) -> Lexer:
  373. """The lexer for this environment."""
  374. return get_lexer(self)
  375. def iter_extensions(self) -> t.Iterator["Extension"]:
  376. """Iterates over the extensions by priority."""
  377. return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
  378. def getitem(
  379. self, obj: t.Any, argument: t.Union[str, t.Any]
  380. ) -> t.Union[t.Any, Undefined]:
  381. """Get an item or attribute of an object but prefer the item."""
  382. try:
  383. return obj[argument]
  384. except (AttributeError, TypeError, LookupError):
  385. if isinstance(argument, str):
  386. try:
  387. attr = str(argument)
  388. except Exception:
  389. pass
  390. else:
  391. try:
  392. return getattr(obj, attr)
  393. except AttributeError:
  394. pass
  395. return self.undefined(obj=obj, name=argument)
  396. def getattr(self, obj: t.Any, attribute: str) -> t.Any:
  397. """Get an item or attribute of an object but prefer the attribute.
  398. Unlike :meth:`getitem` the attribute *must* be a string.
  399. """
  400. try:
  401. return getattr(obj, attribute)
  402. except AttributeError:
  403. pass
  404. try:
  405. return obj[attribute]
  406. except (TypeError, LookupError, AttributeError):
  407. return self.undefined(obj=obj, name=attribute)
  408. def _filter_test_common(
  409. self,
  410. name: t.Union[str, Undefined],
  411. value: t.Any,
  412. args: t.Optional[t.Sequence[t.Any]],
  413. kwargs: t.Optional[t.Mapping[str, t.Any]],
  414. context: t.Optional[Context],
  415. eval_ctx: t.Optional[EvalContext],
  416. is_filter: bool,
  417. ) -> t.Any:
  418. if is_filter:
  419. env_map = self.filters
  420. type_name = "filter"
  421. else:
  422. env_map = self.tests
  423. type_name = "test"
  424. func = env_map.get(name) # type: ignore
  425. if func is None:
  426. msg = f"No {type_name} named {name!r}."
  427. if isinstance(name, Undefined):
  428. try:
  429. name._fail_with_undefined_error()
  430. except Exception as e:
  431. msg = f"{msg} ({e}; did you forget to quote the callable name?)"
  432. raise TemplateRuntimeError(msg)
  433. args = [value, *(args if args is not None else ())]
  434. kwargs = kwargs if kwargs is not None else {}
  435. pass_arg = _PassArg.from_obj(func)
  436. if pass_arg is _PassArg.context:
  437. if context is None:
  438. raise TemplateRuntimeError(
  439. f"Attempted to invoke a context {type_name} without context."
  440. )
  441. args.insert(0, context)
  442. elif pass_arg is _PassArg.eval_context:
  443. if eval_ctx is None:
  444. if context is not None:
  445. eval_ctx = context.eval_ctx
  446. else:
  447. eval_ctx = EvalContext(self)
  448. args.insert(0, eval_ctx)
  449. elif pass_arg is _PassArg.environment:
  450. args.insert(0, self)
  451. return func(*args, **kwargs)
  452. def call_filter(
  453. self,
  454. name: str,
  455. value: t.Any,
  456. args: t.Optional[t.Sequence[t.Any]] = None,
  457. kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
  458. context: t.Optional[Context] = None,
  459. eval_ctx: t.Optional[EvalContext] = None,
  460. ) -> t.Any:
  461. """Invoke a filter on a value the same way the compiler does.
  462. This might return a coroutine if the filter is running from an
  463. environment in async mode and the filter supports async
  464. execution. It's your responsibility to await this if needed.
  465. .. versionadded:: 2.7
  466. """
  467. return self._filter_test_common(
  468. name, value, args, kwargs, context, eval_ctx, True
  469. )
  470. def call_test(
  471. self,
  472. name: str,
  473. value: t.Any,
  474. args: t.Optional[t.Sequence[t.Any]] = None,
  475. kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
  476. context: t.Optional[Context] = None,
  477. eval_ctx: t.Optional[EvalContext] = None,
  478. ) -> t.Any:
  479. """Invoke a test on a value the same way the compiler does.
  480. This might return a coroutine if the test is running from an
  481. environment in async mode and the test supports async execution.
  482. It's your responsibility to await this if needed.
  483. .. versionchanged:: 3.0
  484. Tests support ``@pass_context``, etc. decorators. Added
  485. the ``context`` and ``eval_ctx`` parameters.
  486. .. versionadded:: 2.7
  487. """
  488. return self._filter_test_common(
  489. name, value, args, kwargs, context, eval_ctx, False
  490. )
  491. @internalcode
  492. def parse(
  493. self,
  494. source: str,
  495. name: t.Optional[str] = None,
  496. filename: t.Optional[str] = None,
  497. ) -> nodes.Template:
  498. """Parse the sourcecode and return the abstract syntax tree. This
  499. tree of nodes is used by the compiler to convert the template into
  500. executable source- or bytecode. This is useful for debugging or to
  501. extract information from templates.
  502. If you are :ref:`developing Jinja extensions <writing-extensions>`
  503. this gives you a good overview of the node tree generated.
  504. """
  505. try:
  506. return self._parse(source, name, filename)
  507. except TemplateSyntaxError:
  508. self.handle_exception(source=source)
  509. def _parse(
  510. self, source: str, name: t.Optional[str], filename: t.Optional[str]
  511. ) -> nodes.Template:
  512. """Internal parsing function used by `parse` and `compile`."""
  513. return Parser(self, source, name, filename).parse()
  514. def lex(
  515. self,
  516. source: str,
  517. name: t.Optional[str] = None,
  518. filename: t.Optional[str] = None,
  519. ) -> t.Iterator[t.Tuple[int, str, str]]:
  520. """Lex the given sourcecode and return a generator that yields
  521. tokens as tuples in the form ``(lineno, token_type, value)``.
  522. This can be useful for :ref:`extension development <writing-extensions>`
  523. and debugging templates.
  524. This does not perform preprocessing. If you want the preprocessing
  525. of the extensions to be applied you have to filter source through
  526. the :meth:`preprocess` method.
  527. """
  528. source = str(source)
  529. try:
  530. return self.lexer.tokeniter(source, name, filename)
  531. except TemplateSyntaxError:
  532. self.handle_exception(source=source)
  533. def preprocess(
  534. self,
  535. source: str,
  536. name: t.Optional[str] = None,
  537. filename: t.Optional[str] = None,
  538. ) -> str:
  539. """Preprocesses the source with all extensions. This is automatically
  540. called for all parsing and compiling methods but *not* for :meth:`lex`
  541. because there you usually only want the actual source tokenized.
  542. """
  543. return reduce(
  544. lambda s, e: e.preprocess(s, name, filename),
  545. self.iter_extensions(),
  546. str(source),
  547. )
  548. def _tokenize(
  549. self,
  550. source: str,
  551. name: t.Optional[str],
  552. filename: t.Optional[str] = None,
  553. state: t.Optional[str] = None,
  554. ) -> TokenStream:
  555. """Called by the parser to do the preprocessing and filtering
  556. for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
  557. """
  558. source = self.preprocess(source, name, filename)
  559. stream = self.lexer.tokenize(source, name, filename, state)
  560. for ext in self.iter_extensions():
  561. stream = ext.filter_stream(stream) # type: ignore
  562. if not isinstance(stream, TokenStream):
  563. stream = TokenStream(stream, name, filename) # type: ignore
  564. return stream
  565. def _generate(
  566. self,
  567. source: nodes.Template,
  568. name: t.Optional[str],
  569. filename: t.Optional[str],
  570. defer_init: bool = False,
  571. ) -> str:
  572. """Internal hook that can be overridden to hook a different generate
  573. method in.
  574. .. versionadded:: 2.5
  575. """
  576. return generate( # type: ignore
  577. source,
  578. self,
  579. name,
  580. filename,
  581. defer_init=defer_init,
  582. optimized=self.optimized,
  583. )
  584. def _compile(self, source: str, filename: str) -> CodeType:
  585. """Internal hook that can be overridden to hook a different compile
  586. method in.
  587. .. versionadded:: 2.5
  588. """
  589. return compile(source, filename, "exec") # type: ignore
  590. @typing.overload
  591. def compile( # type: ignore
  592. self,
  593. source: t.Union[str, nodes.Template],
  594. name: t.Optional[str] = None,
  595. filename: t.Optional[str] = None,
  596. raw: "te.Literal[False]" = False,
  597. defer_init: bool = False,
  598. ) -> CodeType:
  599. ...
  600. @typing.overload
  601. def compile(
  602. self,
  603. source: t.Union[str, nodes.Template],
  604. name: t.Optional[str] = None,
  605. filename: t.Optional[str] = None,
  606. raw: "te.Literal[True]" = ...,
  607. defer_init: bool = False,
  608. ) -> str:
  609. ...
  610. @internalcode
  611. def compile(
  612. self,
  613. source: t.Union[str, nodes.Template],
  614. name: t.Optional[str] = None,
  615. filename: t.Optional[str] = None,
  616. raw: bool = False,
  617. defer_init: bool = False,
  618. ) -> t.Union[str, CodeType]:
  619. """Compile a node or template source code. The `name` parameter is
  620. the load name of the template after it was joined using
  621. :meth:`join_path` if necessary, not the filename on the file system.
  622. the `filename` parameter is the estimated filename of the template on
  623. the file system. If the template came from a database or memory this
  624. can be omitted.
  625. The return value of this method is a python code object. If the `raw`
  626. parameter is `True` the return value will be a string with python
  627. code equivalent to the bytecode returned otherwise. This method is
  628. mainly used internally.
  629. `defer_init` is use internally to aid the module code generator. This
  630. causes the generated code to be able to import without the global
  631. environment variable to be set.
  632. .. versionadded:: 2.4
  633. `defer_init` parameter added.
  634. """
  635. source_hint = None
  636. try:
  637. if isinstance(source, str):
  638. source_hint = source
  639. source = self._parse(source, name, filename)
  640. source = self._generate(source, name, filename, defer_init=defer_init)
  641. if raw:
  642. return source
  643. if filename is None:
  644. filename = "<template>"
  645. return self._compile(source, filename)
  646. except TemplateSyntaxError:
  647. self.handle_exception(source=source_hint)
  648. def compile_expression(
  649. self, source: str, undefined_to_none: bool = True
  650. ) -> "TemplateExpression":
  651. """A handy helper method that returns a callable that accepts keyword
  652. arguments that appear as variables in the expression. If called it
  653. returns the result of the expression.
  654. This is useful if applications want to use the same rules as Jinja
  655. in template "configuration files" or similar situations.
  656. Example usage:
  657. >>> env = Environment()
  658. >>> expr = env.compile_expression('foo == 42')
  659. >>> expr(foo=23)
  660. False
  661. >>> expr(foo=42)
  662. True
  663. Per default the return value is converted to `None` if the
  664. expression returns an undefined value. This can be changed
  665. by setting `undefined_to_none` to `False`.
  666. >>> env.compile_expression('var')() is None
  667. True
  668. >>> env.compile_expression('var', undefined_to_none=False)()
  669. Undefined
  670. .. versionadded:: 2.1
  671. """
  672. parser = Parser(self, source, state="variable")
  673. try:
  674. expr = parser.parse_expression()
  675. if not parser.stream.eos:
  676. raise TemplateSyntaxError(
  677. "chunk after expression", parser.stream.current.lineno, None, None
  678. )
  679. expr.set_environment(self)
  680. except TemplateSyntaxError:
  681. self.handle_exception(source=source)
  682. body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
  683. template = self.from_string(nodes.Template(body, lineno=1))
  684. return TemplateExpression(template, undefined_to_none)
  685. def compile_templates(
  686. self,
  687. target: t.Union[str, os.PathLike],
  688. extensions: t.Optional[t.Collection[str]] = None,
  689. filter_func: t.Optional[t.Callable[[str], bool]] = None,
  690. zip: t.Optional[str] = "deflated",
  691. log_function: t.Optional[t.Callable[[str], None]] = None,
  692. ignore_errors: bool = True,
  693. ) -> None:
  694. """Finds all the templates the loader can find, compiles them
  695. and stores them in `target`. If `zip` is `None`, instead of in a
  696. zipfile, the templates will be stored in a directory.
  697. By default a deflate zip algorithm is used. To switch to
  698. the stored algorithm, `zip` can be set to ``'stored'``.
  699. `extensions` and `filter_func` are passed to :meth:`list_templates`.
  700. Each template returned will be compiled to the target folder or
  701. zipfile.
  702. By default template compilation errors are ignored. In case a
  703. log function is provided, errors are logged. If you want template
  704. syntax errors to abort the compilation you can set `ignore_errors`
  705. to `False` and you will get an exception on syntax errors.
  706. .. versionadded:: 2.4
  707. """
  708. from .loaders import ModuleLoader
  709. if log_function is None:
  710. def log_function(x: str) -> None:
  711. pass
  712. assert log_function is not None
  713. assert self.loader is not None, "No loader configured."
  714. def write_file(filename: str, data: str) -> None:
  715. if zip:
  716. info = ZipInfo(filename)
  717. info.external_attr = 0o755 << 16
  718. zip_file.writestr(info, data)
  719. else:
  720. with open(os.path.join(target, filename), "wb") as f:
  721. f.write(data.encode("utf8"))
  722. if zip is not None:
  723. from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
  724. zip_file = ZipFile(
  725. target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
  726. )
  727. log_function(f"Compiling into Zip archive {target!r}")
  728. else:
  729. if not os.path.isdir(target):
  730. os.makedirs(target)
  731. log_function(f"Compiling into folder {target!r}")
  732. try:
  733. for name in self.list_templates(extensions, filter_func):
  734. source, filename, _ = self.loader.get_source(self, name)
  735. try:
  736. code = self.compile(source, name, filename, True, True)
  737. except TemplateSyntaxError as e:
  738. if not ignore_errors:
  739. raise
  740. log_function(f'Could not compile "{name}": {e}')
  741. continue
  742. filename = ModuleLoader.get_module_filename(name)
  743. write_file(filename, code)
  744. log_function(f'Compiled "{name}" as {filename}')
  745. finally:
  746. if zip:
  747. zip_file.close()
  748. log_function("Finished compiling templates")
  749. def list_templates(
  750. self,
  751. extensions: t.Optional[t.Collection[str]] = None,
  752. filter_func: t.Optional[t.Callable[[str], bool]] = None,
  753. ) -> t.List[str]:
  754. """Returns a list of templates for this environment. This requires
  755. that the loader supports the loader's
  756. :meth:`~BaseLoader.list_templates` method.
  757. If there are other files in the template folder besides the
  758. actual templates, the returned list can be filtered. There are two
  759. ways: either `extensions` is set to a list of file extensions for
  760. templates, or a `filter_func` can be provided which is a callable that
  761. is passed a template name and should return `True` if it should end up
  762. in the result list.
  763. If the loader does not support that, a :exc:`TypeError` is raised.
  764. .. versionadded:: 2.4
  765. """
  766. assert self.loader is not None, "No loader configured."
  767. names = self.loader.list_templates()
  768. if extensions is not None:
  769. if filter_func is not None:
  770. raise TypeError(
  771. "either extensions or filter_func can be passed, but not both"
  772. )
  773. def filter_func(x: str) -> bool:
  774. return "." in x and x.rsplit(".", 1)[1] in extensions # type: ignore
  775. if filter_func is not None:
  776. names = [name for name in names if filter_func(name)]
  777. return names
  778. def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
  779. """Exception handling helper. This is used internally to either raise
  780. rewritten exceptions or return a rendered traceback for the template.
  781. """
  782. from .debug import rewrite_traceback_stack
  783. raise rewrite_traceback_stack(source=source)
  784. def join_path(self, template: str, parent: str) -> str:
  785. """Join a template with the parent. By default all the lookups are
  786. relative to the loader root so this method returns the `template`
  787. parameter unchanged, but if the paths should be relative to the
  788. parent template, this function can be used to calculate the real
  789. template name.
  790. Subclasses may override this method and implement template path
  791. joining here.
  792. """
  793. return template
  794. @internalcode
  795. def _load_template(
  796. self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]
  797. ) -> "Template":
  798. if self.loader is None:
  799. raise TypeError("no loader for this environment specified")
  800. cache_key = (weakref.ref(self.loader), name)
  801. if self.cache is not None:
  802. template = self.cache.get(cache_key)
  803. if template is not None and (
  804. not self.auto_reload or template.is_up_to_date
  805. ):
  806. # template.globals is a ChainMap, modifying it will only
  807. # affect the template, not the environment globals.
  808. if globals:
  809. template.globals.update(globals)
  810. return template
  811. template = self.loader.load(self, name, self.make_globals(globals))
  812. if self.cache is not None:
  813. self.cache[cache_key] = template
  814. return template
  815. @internalcode
  816. def get_template(
  817. self,
  818. name: t.Union[str, "Template"],
  819. parent: t.Optional[str] = None,
  820. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  821. ) -> "Template":
  822. """Load a template by name with :attr:`loader` and return a
  823. :class:`Template`. If the template does not exist a
  824. :exc:`TemplateNotFound` exception is raised.
  825. :param name: Name of the template to load. When loading
  826. templates from the filesystem, "/" is used as the path
  827. separator, even on Windows.
  828. :param parent: The name of the parent template importing this
  829. template. :meth:`join_path` can be used to implement name
  830. transformations with this.
  831. :param globals: Extend the environment :attr:`globals` with
  832. these extra variables available for all renders of this
  833. template. If the template has already been loaded and
  834. cached, its globals are updated with any new items.
  835. .. versionchanged:: 3.0
  836. If a template is loaded from cache, ``globals`` will update
  837. the template's globals instead of ignoring the new values.
  838. .. versionchanged:: 2.4
  839. If ``name`` is a :class:`Template` object it is returned
  840. unchanged.
  841. """
  842. if isinstance(name, Template):
  843. return name
  844. if parent is not None:
  845. name = self.join_path(name, parent)
  846. return self._load_template(name, globals)
  847. @internalcode
  848. def select_template(
  849. self,
  850. names: t.Iterable[t.Union[str, "Template"]],
  851. parent: t.Optional[str] = None,
  852. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  853. ) -> "Template":
  854. """Like :meth:`get_template`, but tries loading multiple names.
  855. If none of the names can be loaded a :exc:`TemplatesNotFound`
  856. exception is raised.
  857. :param names: List of template names to try loading in order.
  858. :param parent: The name of the parent template importing this
  859. template. :meth:`join_path` can be used to implement name
  860. transformations with this.
  861. :param globals: Extend the environment :attr:`globals` with
  862. these extra variables available for all renders of this
  863. template. If the template has already been loaded and
  864. cached, its globals are updated with any new items.
  865. .. versionchanged:: 3.0
  866. If a template is loaded from cache, ``globals`` will update
  867. the template's globals instead of ignoring the new values.
  868. .. versionchanged:: 2.11
  869. If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
  870. is raised instead. If no templates were found and ``names``
  871. contains :class:`Undefined`, the message is more helpful.
  872. .. versionchanged:: 2.4
  873. If ``names`` contains a :class:`Template` object it is
  874. returned unchanged.
  875. .. versionadded:: 2.3
  876. """
  877. if isinstance(names, Undefined):
  878. names._fail_with_undefined_error()
  879. if not names:
  880. raise TemplatesNotFound(
  881. message="Tried to select from an empty list of templates."
  882. )
  883. for name in names:
  884. if isinstance(name, Template):
  885. return name
  886. if parent is not None:
  887. name = self.join_path(name, parent)
  888. try:
  889. return self._load_template(name, globals)
  890. except (TemplateNotFound, UndefinedError):
  891. pass
  892. raise TemplatesNotFound(names) # type: ignore
  893. @internalcode
  894. def get_or_select_template(
  895. self,
  896. template_name_or_list: t.Union[
  897. str, "Template", t.List[t.Union[str, "Template"]]
  898. ],
  899. parent: t.Optional[str] = None,
  900. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  901. ) -> "Template":
  902. """Use :meth:`select_template` if an iterable of template names
  903. is given, or :meth:`get_template` if one name is given.
  904. .. versionadded:: 2.3
  905. """
  906. if isinstance(template_name_or_list, (str, Undefined)):
  907. return self.get_template(template_name_or_list, parent, globals)
  908. elif isinstance(template_name_or_list, Template):
  909. return template_name_or_list
  910. return self.select_template(template_name_or_list, parent, globals)
  911. def from_string(
  912. self,
  913. source: t.Union[str, nodes.Template],
  914. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  915. template_class: t.Optional[t.Type["Template"]] = None,
  916. ) -> "Template":
  917. """Load a template from a source string without using
  918. :attr:`loader`.
  919. :param source: Jinja source to compile into a template.
  920. :param globals: Extend the environment :attr:`globals` with
  921. these extra variables available for all renders of this
  922. template. If the template has already been loaded and
  923. cached, its globals are updated with any new items.
  924. :param template_class: Return an instance of this
  925. :class:`Template` class.
  926. """
  927. gs = self.make_globals(globals)
  928. cls = template_class or self.template_class
  929. return cls.from_code(self, self.compile(source), gs, None)
  930. def make_globals(
  931. self, d: t.Optional[t.MutableMapping[str, t.Any]]
  932. ) -> t.MutableMapping[str, t.Any]:
  933. """Make the globals map for a template. Any given template
  934. globals overlay the environment :attr:`globals`.
  935. Returns a :class:`collections.ChainMap`. This allows any changes
  936. to a template's globals to only affect that template, while
  937. changes to the environment's globals are still reflected.
  938. However, avoid modifying any globals after a template is loaded.
  939. :param d: Dict of template-specific globals.
  940. .. versionchanged:: 3.0
  941. Use :class:`collections.ChainMap` to always prevent mutating
  942. environment globals.
  943. """
  944. if d is None:
  945. d = {}
  946. return ChainMap(d, self.globals)
  947. class Template:
  948. """A compiled template that can be rendered.
  949. Use the methods on :class:`Environment` to create or load templates.
  950. The environment is used to configure how templates are compiled and
  951. behave.
  952. It is also possible to create a template object directly. This is
  953. not usually recommended. The constructor takes most of the same
  954. arguments as :class:`Environment`. All templates created with the
  955. same environment arguments share the same ephemeral ``Environment``
  956. instance behind the scenes.
  957. A template object should be considered immutable. Modifications on
  958. the object are not supported.
  959. """
  960. #: Type of environment to create when creating a template directly
  961. #: rather than through an existing environment.
  962. environment_class: t.Type[Environment] = Environment
  963. environment: Environment
  964. globals: t.MutableMapping[str, t.Any]
  965. name: t.Optional[str]
  966. filename: t.Optional[str]
  967. blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]]
  968. root_render_func: t.Callable[[Context], t.Iterator[str]]
  969. _module: t.Optional["TemplateModule"]
  970. _debug_info: str
  971. _uptodate: t.Optional[t.Callable[[], bool]]
  972. def __new__(
  973. cls,
  974. source: t.Union[str, nodes.Template],
  975. block_start_string: str = BLOCK_START_STRING,
  976. block_end_string: str = BLOCK_END_STRING,
  977. variable_start_string: str = VARIABLE_START_STRING,
  978. variable_end_string: str = VARIABLE_END_STRING,
  979. comment_start_string: str = COMMENT_START_STRING,
  980. comment_end_string: str = COMMENT_END_STRING,
  981. line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
  982. line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
  983. trim_blocks: bool = TRIM_BLOCKS,
  984. lstrip_blocks: bool = LSTRIP_BLOCKS,
  985. newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
  986. keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
  987. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
  988. optimized: bool = True,
  989. undefined: t.Type[Undefined] = Undefined,
  990. finalize: t.Optional[t.Callable[..., t.Any]] = None,
  991. autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
  992. enable_async: bool = False,
  993. ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...
  994. env = get_spontaneous_environment(
  995. cls.environment_class, # type: ignore
  996. block_start_string,
  997. block_end_string,
  998. variable_start_string,
  999. variable_end_string,
  1000. comment_start_string,
  1001. comment_end_string,
  1002. line_statement_prefix,
  1003. line_comment_prefix,
  1004. trim_blocks,
  1005. lstrip_blocks,
  1006. newline_sequence,
  1007. keep_trailing_newline,
  1008. frozenset(extensions),
  1009. optimized,
  1010. undefined, # type: ignore
  1011. finalize,
  1012. autoescape,
  1013. None,
  1014. 0,
  1015. False,
  1016. None,
  1017. enable_async,
  1018. )
  1019. return env.from_string(source, template_class=cls)
  1020. @classmethod
  1021. def from_code(
  1022. cls,
  1023. environment: Environment,
  1024. code: CodeType,
  1025. globals: t.MutableMapping[str, t.Any],
  1026. uptodate: t.Optional[t.Callable[[], bool]] = None,
  1027. ) -> "Template":
  1028. """Creates a template object from compiled code and the globals. This
  1029. is used by the loaders and environment to create a template object.
  1030. """
  1031. namespace = {"environment": environment, "__file__": code.co_filename}
  1032. exec(code, namespace)
  1033. rv = cls._from_namespace(environment, namespace, globals)
  1034. rv._uptodate = uptodate
  1035. return rv
  1036. @classmethod
  1037. def from_module_dict(
  1038. cls,
  1039. environment: Environment,
  1040. module_dict: t.MutableMapping[str, t.Any],
  1041. globals: t.MutableMapping[str, t.Any],
  1042. ) -> "Template":
  1043. """Creates a template object from a module. This is used by the
  1044. module loader to create a template object.
  1045. .. versionadded:: 2.4
  1046. """
  1047. return cls._from_namespace(environment, module_dict, globals)
  1048. @classmethod
  1049. def _from_namespace(
  1050. cls,
  1051. environment: Environment,
  1052. namespace: t.MutableMapping[str, t.Any],
  1053. globals: t.MutableMapping[str, t.Any],
  1054. ) -> "Template":
  1055. t: "Template" = object.__new__(cls)
  1056. t.environment = environment
  1057. t.globals = globals
  1058. t.name = namespace["name"]
  1059. t.filename = namespace["__file__"]
  1060. t.blocks = namespace["blocks"]
  1061. # render function and module
  1062. t.root_render_func = namespace["root"] # type: ignore
  1063. t._module = None
  1064. # debug and loader helpers
  1065. t._debug_info = namespace["debug_info"]
  1066. t._uptodate = None
  1067. # store the reference
  1068. namespace["environment"] = environment
  1069. namespace["__jinja_template__"] = t
  1070. return t
  1071. def render(self, *args: t.Any, **kwargs: t.Any) -> str:
  1072. """This method accepts the same arguments as the `dict` constructor:
  1073. A dict, a dict subclass or some keyword arguments. If no arguments
  1074. are given the context will be empty. These two calls do the same::
  1075. template.render(knights='that say nih')
  1076. template.render({'knights': 'that say nih'})
  1077. This will return the rendered template as a string.
  1078. """
  1079. if self.environment.is_async:
  1080. import asyncio
  1081. close = False
  1082. try:
  1083. loop = asyncio.get_running_loop()
  1084. except RuntimeError:
  1085. loop = asyncio.new_event_loop()
  1086. close = True
  1087. try:
  1088. return loop.run_until_complete(self.render_async(*args, **kwargs))
  1089. finally:
  1090. if close:
  1091. loop.close()
  1092. ctx = self.new_context(dict(*args, **kwargs))
  1093. try:
  1094. return self.environment.concat(self.root_render_func(ctx)) # type: ignore
  1095. except Exception:
  1096. self.environment.handle_exception()
  1097. async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:
  1098. """This works similar to :meth:`render` but returns a coroutine
  1099. that when awaited returns the entire rendered template string. This
  1100. requires the async feature to be enabled.
  1101. Example usage::
  1102. await template.render_async(knights='that say nih; asynchronously')
  1103. """
  1104. if not self.environment.is_async:
  1105. raise RuntimeError(
  1106. "The environment was not created with async mode enabled."
  1107. )
  1108. ctx = self.new_context(dict(*args, **kwargs))
  1109. try:
  1110. return self.environment.concat( # type: ignore
  1111. [n async for n in self.root_render_func(ctx)] # type: ignore
  1112. )
  1113. except Exception:
  1114. return self.environment.handle_exception()
  1115. def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":
  1116. """Works exactly like :meth:`generate` but returns a
  1117. :class:`TemplateStream`.
  1118. """
  1119. return TemplateStream(self.generate(*args, **kwargs))
  1120. def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:
  1121. """For very large templates it can be useful to not render the whole
  1122. template at once but evaluate each statement after another and yield
  1123. piece for piece. This method basically does exactly that and returns
  1124. a generator that yields one item after another as strings.
  1125. It accepts the same arguments as :meth:`render`.
  1126. """
  1127. if self.environment.is_async:
  1128. import asyncio
  1129. async def to_list() -> t.List[str]:
  1130. return [x async for x in self.generate_async(*args, **kwargs)]
  1131. yield from asyncio.run(to_list())
  1132. return
  1133. ctx = self.new_context(dict(*args, **kwargs))
  1134. try:
  1135. yield from self.root_render_func(ctx) # type: ignore
  1136. except Exception:
  1137. yield self.environment.handle_exception()
  1138. async def generate_async(
  1139. self, *args: t.Any, **kwargs: t.Any
  1140. ) -> t.AsyncIterator[str]:
  1141. """An async version of :meth:`generate`. Works very similarly but
  1142. returns an async iterator instead.
  1143. """
  1144. if not self.environment.is_async:
  1145. raise RuntimeError(
  1146. "The environment was not created with async mode enabled."
  1147. )
  1148. ctx = self.new_context(dict(*args, **kwargs))
  1149. try:
  1150. async for event in self.root_render_func(ctx): # type: ignore
  1151. yield event
  1152. except Exception:
  1153. yield self.environment.handle_exception()
  1154. def new_context(
  1155. self,
  1156. vars: t.Optional[t.Dict[str, t.Any]] = None,
  1157. shared: bool = False,
  1158. locals: t.Optional[t.Mapping[str, t.Any]] = None,
  1159. ) -> Context:
  1160. """Create a new :class:`Context` for this template. The vars
  1161. provided will be passed to the template. Per default the globals
  1162. are added to the context. If shared is set to `True` the data
  1163. is passed as is to the context without adding the globals.
  1164. `locals` can be a dict of local variables for internal usage.
  1165. """
  1166. return new_context(
  1167. self.environment, self.name, self.blocks, vars, shared, self.globals, locals
  1168. )
  1169. def make_module(
  1170. self,
  1171. vars: t.Optional[t.Dict[str, t.Any]] = None,
  1172. shared: bool = False,
  1173. locals: t.Optional[t.Mapping[str, t.Any]] = None,
  1174. ) -> "TemplateModule":
  1175. """This method works like the :attr:`module` attribute when called
  1176. without arguments but it will evaluate the template on every call
  1177. rather than caching it. It's also possible to provide
  1178. a dict which is then used as context. The arguments are the same
  1179. as for the :meth:`new_context` method.
  1180. """
  1181. ctx = self.new_context(vars, shared, locals)
  1182. return TemplateModule(self, ctx)
  1183. async def make_module_async(
  1184. self,
  1185. vars: t.Optional[t.Dict[str, t.Any]] = None,
  1186. shared: bool = False,
  1187. locals: t.Optional[t.Mapping[str, t.Any]] = None,
  1188. ) -> "TemplateModule":
  1189. """As template module creation can invoke template code for
  1190. asynchronous executions this method must be used instead of the
  1191. normal :meth:`make_module` one. Likewise the module attribute
  1192. becomes unavailable in async mode.
  1193. """
  1194. ctx = self.new_context(vars, shared, locals)
  1195. return TemplateModule(
  1196. self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore
  1197. )
  1198. @internalcode
  1199. def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":
  1200. """If a context is passed in, this means that the template was
  1201. imported. Imported templates have access to the current
  1202. template's globals by default, but they can only be accessed via
  1203. the context during runtime.
  1204. If there are new globals, we need to create a new module because
  1205. the cached module is already rendered and will not have access
  1206. to globals from the current context. This new module is not
  1207. cached because the template can be imported elsewhere, and it
  1208. should have access to only the current template's globals.
  1209. """
  1210. if self.environment.is_async:
  1211. raise RuntimeError("Module is not available in async mode.")
  1212. if ctx is not None:
  1213. keys = ctx.globals_keys - self.globals.keys()
  1214. if keys:
  1215. return self.make_module({k: ctx.parent[k] for k in keys})
  1216. if self._module is None:
  1217. self._module = self.make_module()
  1218. return self._module
  1219. async def _get_default_module_async(
  1220. self, ctx: t.Optional[Context] = None
  1221. ) -> "TemplateModule":
  1222. if ctx is not None:
  1223. keys = ctx.globals_keys - self.globals.keys()
  1224. if keys:
  1225. return await self.make_module_async({k: ctx.parent[k] for k in keys})
  1226. if self._module is None:
  1227. self._module = await self.make_module_async()
  1228. return self._module
  1229. @property
  1230. def module(self) -> "TemplateModule":
  1231. """The template as module. This is used for imports in the
  1232. template runtime but is also useful if one wants to access
  1233. exported template variables from the Python layer:
  1234. >>> t = Template('{% macro foo() %}42{% endmacro %}23')
  1235. >>> str(t.module)
  1236. '23'
  1237. >>> t.module.foo() == u'42'
  1238. True
  1239. This attribute is not available if async mode is enabled.
  1240. """
  1241. return self._get_default_module()
  1242. def get_corresponding_lineno(self, lineno: int) -> int:
  1243. """Return the source line number of a line number in the
  1244. generated bytecode as they are not in sync.
  1245. """
  1246. for template_line, code_line in reversed(self.debug_info):
  1247. if code_line <= lineno:
  1248. return template_line
  1249. return 1
  1250. @property
  1251. def is_up_to_date(self) -> bool:
  1252. """If this variable is `False` there is a newer version available."""
  1253. if self._uptodate is None:
  1254. return True
  1255. return self._uptodate()
  1256. @property
  1257. def debug_info(self) -> t.List[t.Tuple[int, int]]:
  1258. """The debug info mapping."""
  1259. if self._debug_info:
  1260. return [
  1261. tuple(map(int, x.split("="))) # type: ignore
  1262. for x in self._debug_info.split("&")
  1263. ]
  1264. return []
  1265. def __repr__(self) -> str:
  1266. if self.name is None:
  1267. name = f"memory:{id(self):x}"
  1268. else:
  1269. name = repr(self.name)
  1270. return f"<{type(self).__name__} {name}>"
  1271. class TemplateModule:
  1272. """Represents an imported template. All the exported names of the
  1273. template are available as attributes on this object. Additionally
  1274. converting it into a string renders the contents.
  1275. """
  1276. def __init__(
  1277. self,
  1278. template: Template,
  1279. context: Context,
  1280. body_stream: t.Optional[t.Iterable[str]] = None,
  1281. ) -> None:
  1282. if body_stream is None:
  1283. if context.environment.is_async:
  1284. raise RuntimeError(
  1285. "Async mode requires a body stream to be passed to"
  1286. " a template module. Use the async methods of the"
  1287. " API you are using."
  1288. )
  1289. body_stream = list(template.root_render_func(context)) # type: ignore
  1290. self._body_stream = body_stream
  1291. self.__dict__.update(context.get_exported())
  1292. self.__name__ = template.name
  1293. def __html__(self) -> Markup:
  1294. return Markup(concat(self._body_stream))
  1295. def __str__(self) -> str:
  1296. return concat(self._body_stream)
  1297. def __repr__(self) -> str:
  1298. if self.__name__ is None:
  1299. name = f"memory:{id(self):x}"
  1300. else:
  1301. name = repr(self.__name__)
  1302. return f"<{type(self).__name__} {name}>"
  1303. class TemplateExpression:
  1304. """The :meth:`jinja2.Environment.compile_expression` method returns an
  1305. instance of this object. It encapsulates the expression-like access
  1306. to the template with an expression it wraps.
  1307. """
  1308. def __init__(self, template: Template, undefined_to_none: bool) -> None:
  1309. self._template = template
  1310. self._undefined_to_none = undefined_to_none
  1311. def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]:
  1312. context = self._template.new_context(dict(*args, **kwargs))
  1313. consume(self._template.root_render_func(context)) # type: ignore
  1314. rv = context.vars["result"]
  1315. if self._undefined_to_none and isinstance(rv, Undefined):
  1316. rv = None
  1317. return rv
  1318. class TemplateStream:
  1319. """A template stream works pretty much like an ordinary python generator
  1320. but it can buffer multiple items to reduce the number of total iterations.
  1321. Per default the output is unbuffered which means that for every unbuffered
  1322. instruction in the template one string is yielded.
  1323. If buffering is enabled with a buffer size of 5, five items are combined
  1324. into a new string. This is mainly useful if you are streaming
  1325. big templates to a client via WSGI which flushes after each iteration.
  1326. """
  1327. def __init__(self, gen: t.Iterator[str]) -> None:
  1328. self._gen = gen
  1329. self.disable_buffering()
  1330. def dump(
  1331. self,
  1332. fp: t.Union[str, t.IO],
  1333. encoding: t.Optional[str] = None,
  1334. errors: t.Optional[str] = "strict",
  1335. ) -> None:
  1336. """Dump the complete stream into a file or file-like object.
  1337. Per default strings are written, if you want to encode
  1338. before writing specify an `encoding`.
  1339. Example usage::
  1340. Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
  1341. """
  1342. close = False
  1343. if isinstance(fp, str):
  1344. if encoding is None:
  1345. encoding = "utf-8"
  1346. fp = open(fp, "wb")
  1347. close = True
  1348. try:
  1349. if encoding is not None:
  1350. iterable = (x.encode(encoding, errors) for x in self) # type: ignore
  1351. else:
  1352. iterable = self # type: ignore
  1353. if hasattr(fp, "writelines"):
  1354. fp.writelines(iterable)
  1355. else:
  1356. for item in iterable:
  1357. fp.write(item)
  1358. finally:
  1359. if close:
  1360. fp.close()
  1361. def disable_buffering(self) -> None:
  1362. """Disable the output buffering."""
  1363. self._next = partial(next, self._gen)
  1364. self.buffered = False
  1365. def _buffered_generator(self, size: int) -> t.Iterator[str]:
  1366. buf: t.List[str] = []
  1367. c_size = 0
  1368. push = buf.append
  1369. while True:
  1370. try:
  1371. while c_size < size:
  1372. c = next(self._gen)
  1373. push(c)
  1374. if c:
  1375. c_size += 1
  1376. except StopIteration:
  1377. if not c_size:
  1378. return
  1379. yield concat(buf)
  1380. del buf[:]
  1381. c_size = 0
  1382. def enable_buffering(self, size: int = 5) -> None:
  1383. """Enable buffering. Buffer `size` items before yielding them."""
  1384. if size <= 1:
  1385. raise ValueError("buffer size too small")
  1386. self.buffered = True
  1387. self._next = partial(next, self._buffered_generator(size))
  1388. def __iter__(self) -> "TemplateStream":
  1389. return self
  1390. def __next__(self) -> str:
  1391. return self._next() # type: ignore
  1392. # hook in default template class. if anyone reads this comment: ignore that
  1393. # it's possible to use custom templates ;-)
  1394. Environment.template_class = Template